// pages/my/my.js
import Toast from '../../miniprogram_npm/vant-weapp/toast/toast';
const app = getApp();
const db = wx.cloud.database();

const moviex_col = db.collection('movies');
const goods_col = db.collection('goods');
const hotDatas_col = db.collection('hotDatas');
const logins_col = db.collection('logins');

Page({
  data: {
    userInfo: {},
    moviesData: [],
    collectNum: '',
    hasUserInfo: false,
    isShowOne: false,
    isShowTwo: true,
    loginLength: '',
    loginId: '',
    signCode: '',
  },
  
  onLoad: function () {
    // 状态栏样式
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
    });

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 请求登录信息
    logins_col.get({
      success: function(res) {
        // res.data 包含该记录的数据
        this.data.loginLength = res.data.length;
      }
    });    
  },

  //点击头像跳转
  bindViewTap: function() {
    Toast.loading({
      duration: 500,
      message: '加载中...',
      forbidClick: true,
      onClose: () => {
        wx.navigateTo({
          url: '/pages/loginDetails/loginDetails?id='+this.data.loginId,
        })
      }
    })
  },

  // 获取登录信息
  getUserInfo: function() {
    var self = this;
    var newLength = self.data.loginLength;
    wx.getUserProfile({
      lang:'zh_CN',//请求信息返回的数据语言
      desc:'登录信息使用',//请求使用用途
      success: res =>{
        // console.log(res,'信息');
        app.globalData.userInfo = res.userInfo;
  
        // 获取登录token
        wx.login({
          success (resOne) {
            if (resOne.code) {
              //发起网络请求
              app.globalData.code = resOne.code;
              self.data.signCode = resOne.code;
            } else {
              console.log('登录失败！' + resOne.errMsg)
            }
          }
        });

        // 存信息到云数据库
        logins_col.where({
          username: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl,
        }).get({
          success: function(resTwo) {
            if(resTwo.data.length !== 0){
              app.globalData.userId = resTwo.data[0]._id;
              self.data.loginId = resTwo.data[0]._id;
              self.loadmoviesList();
              wx.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 2000
              });
              self.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              });    
            }else{
              logins_col.add({
                data: {
                  _id: String(newLength + 1),
                  username: app.globalData.userInfo.nickName,
                  avatarUrl: app.globalData.userInfo.avatarUrl,
                  telephone: "",
                  address: "",
                  sex: String(app.globalData.userInfo.gender),
                  area: app.globalData.userInfo.country,
                },
                success: function(ghj) {
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success',
                    duration: 2000
                  });
                  self.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                  }); 
                },
              })
            }       
          },
        })
      },
      error: () => {
        wx.showToast({
          title: '登录失败',
          icon: 'error',
          duration: 2000
        })   
      },
    });
    
  },

  // 意见页面跳转
  getIdea: function() {
    if(this.data.signCode !== "" && this.data.loginId !== ''){
      wx.navigateTo({
        url: '/pages/ideas/ideas',
      })
    }else if(this.data.signCode !== "" && this.data.loginId == ''){
      wx.showToast({
        title: '网络不可用',
        icon: "error",
        duration: 2000
      })    
    }else{
      wx.showToast({
        title: '未登录!',
        icon: "error",
        duration: 2000
      })      
    }
  },

  // 实时更新我的收藏
   loadmoviesList: function() {
    var self = this;
    self.gettvData();
    moviex_col.watch({
      onChange: function() {
        self.gettvData();
      },
      onError: function() {
        console.error('the watch closed because of error')
      }
    });
    goods_col.watch({
      onChange: function() {
        self.gettvData();
      },
      onError: function() {
        console.error('the watch closed because of error')
      }
    });
    hotDatas_col.watch({
      onChange: function() {
        self.gettvData();
      },
      onError: function() {
        console.error('the watch closed because of error')
      }
    });
    
  },

  // 请求我的收藏
  async gettvData(){
    let resOne = await moviex_col.get();
    let resTwo = await goods_col.get();
    let resThree = await hotDatas_col.get();
    let newLoginId = this.data.loginId;
    let newOne = resOne.data;
    let newTwo = resTwo.data;
    let newThree = resThree.data;
    var moviesCollect = [];
    newOne.forEach( item => {
      if(item.collected == true && item.userId == newLoginId){
        moviesCollect.push(item)
      }
    });
    newTwo.forEach( item => {
      if(item.collected == true && item.userId == newLoginId){
        moviesCollect.push(item)
      }
    });
    newThree.forEach( item => {
      if(item.collected == true && item.userId == newLoginId){
        moviesCollect.push(item)
      }
    });
    // 判断显示与隐藏
    if(moviesCollect.length > 0){
      this.setData({
        isShowOne: true,
        isShowTwo: false,
        moviesData: moviesCollect,
        collectNum: moviesCollect.length,
      })
    }else{
      this.setData({
        isShowOne: false,
        isShowTwo: true
      })
    }
  },

  // 点击收藏信息跳转到详情
  selectOne: function (event) {
    Toast.loading({
      duration: 1100,
      message: '加载中...',
      forbidClick: true,
      onClose: () => {
        // 点击新闻列表项，携带id跳转新闻详情页面
        var id = event.currentTarget.dataset.detailid;
        var newSign = event.currentTarget.dataset.sign;
        var newtype = event.currentTarget.dataset.type;

        switch(newtype){
          case "tv":
            wx.navigateTo({
              url: '/pages/tvDetails/tvDetails?id='+id,
            })
            break;
          case "essay":
            wx.navigateTo({
              url: '/pages/details/details?id='+id + '&sign=' +newSign,
            })
            break;
        };
      },
    });
  }
})
